package com.novabluetooth.views;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.List;

import com.health.NovaApplication;
import com.health.R;
import com.health.tablebean.BTDevice;
import com.health.tools.SPUtil;
import com.nova.BaseActivity;
import com.nova.view.BaseSharedPreferencesUtil;
import com.nova.view.NovaLog;
import com.novabluetooth.adapter.SBCLMenuGridAdapter;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.data.GlobalContsBlueThooth;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.services.TJBluetoothLeService;
import com.novabluetooth.services.bluetooth2.ListenService;
import com.novabluetooth.services.hqxd.HQXDActivity;
import com.novabluetooth.services.servicedevices.NiaoJiht111AHanTangService;
import com.novabluetooth.services.servicedevices.TiWenHtdService;
import com.novabluetooth.services.servicedevices.TiWenNovaService;
import com.novabluetooth.services.servicedevices.TiZhongNovaService;
import com.novabluetooth.services.servicedevices.WeiTaiXueTangService;
import com.novabluetooth.services.servicedevices.XueTangAWXSanNuoService;
import com.novabluetooth.services.servicedevices.XueTangWL1SanNuoService;
import com.novabluetooth.services.servicedevices.XueYaB61TJMRService;
import com.novabluetooth.services.servicedevices.XueYaYuYue760Service;
import com.novabluetooth.services.servicedevices.XueYangKRKService;
import com.novabluetooth.services.servicedevices.XueYangNovaService;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 设备测量主界面
 * 
 * @author nova
 *
 */
public class SBCLActivity extends BaseActivity implements OnClickListener {
	public static int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
	public static String EW = "EW";
	public static String EW_ERRORMSG = "EW_ERRORMSG";
	private static String TAG = "SBCLActivity";
	private GridView gd_view;
	private TextView blueToothState;
	// 测量过程中交互的空间

	private LinearLayout lay_result, lay_celiang;
	private TextView tv_result, tv_state;
	private Button bt_celiang, bt_cklsjl, bt_bindDevices, btn_back;
	private ImageView show_img;
	String typename = "";
	boolean isBlooth2 = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bluetooth_sbcl_main);
		isBlooth2 = SPUtil.getisBlooth2(SBCLActivity.this, false);
		try {
			findViews();
			setListeners();
			initBleModular();
			initBluetooth();
			registBroadCast();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void findViews() {
		gd_view = (GridView) findViewById(R.id.gd_view);
		SBCLMenuGridAdapter gdAdapter = new SBCLMenuGridAdapter(SBCLActivity.this);
		gd_view.setAdapter(gdAdapter);
		blueToothState = (TextView) findViewById(R.id.blueToothState);
		lay_result = (LinearLayout) findViewById(R.id.lay_result);
		lay_celiang = (LinearLayout) findViewById(R.id.lay_start);

		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);

		tv_result = (TextView) findViewById(R.id.tv_result);
		tv_state = (TextView) findViewById(R.id.tv_state);

		bt_celiang = (Button) findViewById(R.id.bt_start);
		bt_celiang.setOnClickListener(this);
		bt_cklsjl = (Button) findViewById(R.id.bt_cklsjl);
		bt_bindDevices = (Button) findViewById(R.id.bt_bindDevices);
		bt_cklsjl.setOnClickListener(this);
		bt_bindDevices.setOnClickListener(this);
		show_img = (ImageView) findViewById(R.id.show_img);
	}

	private void setListeners() {
		gd_view.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// BloothTool bloothTool = new BloothTool(MainActivity.this);
				// bloothTool.scanLeDevice(true);
				view.setSelected(true);
				queryIndex = "";
				if (position == 0) {
					queryIndex = BluetoothConstant.TIWEN;
					typename = BluetoothConstant.TIWEN_TYPENAME;
				} else if (position == 1) {
					queryIndex = BluetoothConstant.XUEYA;
					typename = BluetoothConstant.XUEYA_TYPENAME;
				} else if (position == 2) {
					queryIndex = BluetoothConstant.XUETANG;
					typename = BluetoothConstant.XUETANG_TYPENAME;
				} else if (position == 3) {
					queryIndex = BluetoothConstant.TIZHONG;
					typename = BluetoothConstant.TIZHONG_TYPENAME;
				} else if (position == 4) {
					queryIndex = BluetoothConstant.XUEYANG;
					typename = BluetoothConstant.XUEYANG_TYPENAME;
				} else if (position == 5) {
					queryIndex = BluetoothConstant.NIAOCHANGGUI;
					typename = BluetoothConstant.NIAOCHANGGUI_TYPENAME;
				}

				if (!TextUtils.isEmpty(queryIndex)) {
					cleanDeviceData();
					if (queryIndex.equals(BluetoothConstant.NIAOCHANGGUI)) {
						tv_state.setText("请先在尿机设备中测量完成后，再点击开始测量。");
					} else if (queryIndex.equals(BluetoothConstant.XUETANG)) {
						tv_state.setText("若需连续测量，请每次测量间隔   30秒。");
					} else if (queryIndex.equals(BluetoothConstant.XUEYANG)) {
						tv_state.setText("科瑞康血氧若需连续测量，请每次测量间隔   30秒。");
					} else if (queryIndex.equals(BluetoothConstant.TIZHONG)) {
						tv_state.setText("请先在体重设备中测量完成后，再点击开始测量。");
					} else {
						tv_state.setText("");
					}
					bt_cklsjl.setText("查看" + typename + "历史数据");
					// typename = BluetoothConstant.getCLTypeName(queryIndex);
					// startCLDevice();
				} else {
					showTextDialog("请先选择测量项目");
				}

			}
		});
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btn_back) {
			SBCLActivity.this.finish();
		} else if (id == R.id.bt_start) {
			// 开始测量
			if (!TextUtils.isEmpty(queryIndex)) {
				startCLDevice();
			} else {
				showTextDialog("请先选择测量项目");
			}
		} else if (id == R.id.bt_bindDevices) {
			// 绑定设备
			Intent intent = new Intent(SBCLActivity.this, BluetoothDeviceBindActivity2.class);
			startActivity(intent);
		} else if (id == R.id.bt_cklsjl) {
			// 查看历史数据
			ckCLHistoryData();
		} else {
		}

	}

	/**
	 * 查看历史记录
	 * 
	 * @author 王婷婷
	 * @date 2017年7月14日 下午2:33:48
	 */
	private void ckCLHistoryData() {
		String typename = BluetoothConstant.getCLTypeName(queryIndex);
		if (TextUtils.isEmpty(typename)) {
			showTextDialog("请先选择测量项目");
		} else {
			Intent intent2 = new Intent(SBCLActivity.this, ExamHistoryActivity.class);
			intent2.putExtra("flag", typename);
			startActivity(intent2);
			// startActivityForResult(intent2, GlobalConts.RequestTiwen);
		}

	}

	/***
	 * 清空数据
	 * 
	 * @author 王婷婷
	 * @date 2017年7月14日 下午2:34:23
	 */
	private void cleanDeviceData() {
		lay_result.setVisibility(View.GONE);
		tv_state.setText("");
		tv_result.setText("");
		show_img.setVisibility(View.GONE);

		// closeAndExit();
	}

	// --------------------注册心电-----------------------------------------------------
	MsgReceiver msgReceiver;

	/**
	 * 注册服务广播
	 * 
	 * @author 王婷婷
	 * @date 2015年12月18日 上午11:18:47
	 */
	private void registBroadCast() {
		// 动态注册广播接收器
		msgReceiver = new MsgReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BluetoothConstant.REGISTER_GB);
		intentFilter.addAction(BluetoothConstant.REGISTER_EW);
		intentFilter.addAction(BluetoothConstant.REGISTER_Waiting);
		intentFilter.addAction(BluetoothConstant.XUEYA_MAIBOBO1);
		System.out.println("广播已注册");
		registerReceiver(msgReceiver, intentFilter);

	}

	/**
	 * 广播接收器
	 * 
	 * @author len Yuwell BloodPressure可以关闭蓝牙了
	 * 
	 */
	public class MsgReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, final Intent intent) {
			if (BluetoothConstant.REGISTER_GB.equals(intent.getAction())) {
				// 拿到进度，更新UI
				try {
					Log.e(TAG, "MsgReceiver 广播接收器");
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							initEcgJpg(intent);
							// stopService(new Intent(SBCLActivity.this,
							// ListenService.class));
						}
					});

				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (BluetoothConstant.REGISTER_EW.equals(intent.getAction())) {
				String ewValue = intent.getBundleExtra("ewValue").getFloat(SBCLActivity.EW) + "";
				mDeviceName = "NOVAEW";
				if (TextUtils.isEmpty(ewValue)) {
					String ewValue_errorMsg = intent.getBundleExtra("ewValue").getString(SBCLActivity.EW_ERRORMSG) + "";
					if (!TextUtils.isEmpty(ewValue_errorMsg)) {
						tv_state.setText(ewValue_errorMsg + "，请重新测量！");
					}
				} else {
					showData(ewValue);
				}

			} else if (BluetoothConstant.XUEYA_MAIBOBO1.equals(intent.getAction())) {
				// 拿到进度，更新UI
				try {
					Log.e(TAG, "MsgReceiver 广播接收器");
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							String bloodValue = intent.getStringExtra("bloodValue");
							Log.e(TAG, "bloodValue"+bloodValue);
							mDeviceName = BluetoothConstant.XUEYA_MAIBOBO1;
							if (TextUtils.isEmpty(bloodValue)) {
								tv_state.setText("请重新测量！");
							} else {
								showData(bloodValue);
							}

						}
					});

				} catch (Exception e) {
					e.printStackTrace();
				}
			}  else if (BluetoothConstant.REGISTER_Waiting.equals(intent.getAction())) {
				showProgressDialog("等待接收数据");
			}

		}
	}

	// --------------------------------蓝牙数据处理-------------------------------------------
	/**
	 * 蓝牙处理
	 * 
	 * @author 王婷婷
	 * @date 2017年7月14日 上午11:54:45
	 */
	private void startCLDevice() {
		cleanDeviceData();
		Log.e(TAG, "isBlooth2：" + isBlooth2);

		if (BluetoothConstant.ECG.equals(queryIndex)) {
			bt_cklsjl.setText("查看心电历史数据");
			// 心电
			Intent intent = new Intent(SBCLActivity.this, HQXDActivity.class);
			startActivity(intent);
		}else {

			if (BluetoothConstant.TIWEN.equals(queryIndex)) {
				// 体温
				if (isBlooth2) {
					initBluetooth2();
				} else {
					initBleModular();
					initBluetooth();
					scanLeDevice(true);
				}

			}else if (BluetoothConstant.XUEYA.equals(queryIndex)) {
				Intent intent = new Intent(SBCLActivity.this, BluetoothConnMeasureActivity.class);
				startActivity(intent);
			}  else {
				initBleModular();
				initBluetooth();
				scanLeDevice(true);

			}

		}

	}

	BluetoothAdapter mBluetoothAdapter;// ble
	BluetoothManager mBluetoothManager;
	// private BluetoothAdapter mBluetoothAdapter2;// 蓝牙2.0
	public SharedPreferences preferences;
	public SharedPreferences.Editor editor;
	private Intent intent = new Intent("com.example.communication.RECEIVER");

	public final String DEVICE_NAME = "device_name";
	public final String GET_VALUE = "getValue";
	public final String TOAST = "toast";
	public final int MESSAGE_STATE_CHANGE = 1;
	public final int MESSAGE_READ = 2;
	public final int MESSAGE_WRITE = 3;
	public final int MESSAGE_DEVICE_NAME = 4;
	public final int MESSAGE_TOAST = 5;

	public boolean ifState = false;
	TJBluetoothLeService mBluetoothLeService;
	String mDeviceAddress;
	String mDeviceName;
	Date date_pre_yyxyj = null;// 鱼跃血压计
	Date date_pre_krkxy = null;// 科瑞康血氧
	Date date_pre_htdewq = null;// 和泰达耳温枪
	// Handler mHandler = new Handler();
	boolean mScanning, isReceive;
	// Stops scanning after 10 seconds.
	private boolean isRegisterReceiver = false;
	private boolean isBound = false;
	private String queryIndex;

	private void initBluetooth() {

		Log.w("eeeeeeeeeeeeee----------", "设备服务---开启");
		preferences = mContext.getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
		editor = preferences.edit();
		// initBleModular();
		mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		isRegisterReceiver = true;
	}

	/**
	 * 初始化蓝牙信息
	 * 
	 * @author 王婷婷
	 * @date 2017年7月12日 下午2:49:29
	 */
	private void initBleModular() {

		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
			blueToothState.setText("该PAD不支持蓝牙4.0");
			return;
		}

		mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter = mBluetoothManager.getAdapter();

		// Checks if Bluetooth is supported on the device.
		if (mBluetoothAdapter == null) {
			blueToothState.setText("该PAD不支持蓝牙");
			return;
		}

		// TODO 开启蓝牙，开始测量
		if (!mBluetoothAdapter.isEnabled()) {
			boolean flag = mBluetoothAdapter.enable();
			// 开启蓝牙成功还是失败
			if (flag) {
				blueToothState.setText("蓝牙已打开");
			} else {
				blueToothState.setText("自动开启蓝牙失败，请在【系统设置】--【蓝牙】手动开启蓝牙");
			}

		} else {
			blueToothState.setText("蓝牙已打开");
		}

	}

	private Handler mHandler = new Handler();
	// Stops scanning after 10 seconds.
	private static final long SCAN_PERIOD = 60000;

	/**
	 * 进行蓝牙设备的扫描
	 * 
	 * @param enable
	 * @author 王婷婷
	 * @date 2017年7月12日 下午2:50:10
	 */
	private void scanLeDevice(final boolean enable) {

		if (enable) {
			// Stops scanning after a pre-defined scan period.
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (mScanning) {
						cancelProgressDialog();
						lay_celiang.setVisibility(View.VISIBLE);
						mScanning = false;
						mBluetoothAdapter.stopLeScan(mLeScanCallback);
					}
				}
			}, SCAN_PERIOD);
			if (!TextUtils.isEmpty(typename)) {
				showProgressDialog("正在搜索" + typename + "设备");
			} else {
				showProgressDialog("正在搜索设备");
			}

			mScanning = true;
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			cancelProgressDialog();
			if (mScanning) {
				lay_celiang.setVisibility(View.VISIBLE);
			}
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
			// showTextDialog("未搜索到" + typename + "设备");
		}
	}

	// Device scan callback.
	private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

		@Override
		public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					Log.e("QueryIndex", "QueryIndex"+"======="+queryIndex);
					Log.e("device.getName()", "device.getName()"+"======="+device.getName());

					if (!TextUtils.isEmpty(device.getName())) {
						if (TextUtils.isEmpty(queryIndex)) {
							return;
						}
						Log.e(TAG, device.getName() + "\n" + queryIndex);
						switch (queryIndex) {
						case BluetoothConstant.TIZHONG:
							if (!BluetoothConstant.TIZHONG_NOVA.equals(device.getName())) {
								return;
							}
							break;
						case BluetoothConstant.TIWEN:
							if (!BluetoothConstant.TIWEN_EWQ_NOVA.equals(device.getName())
									&& !BluetoothConstant.TIWEN_EWQ_HTD.equals(device.getName())
									&& !BluetoothConstant.TIWEN_EWENQ_HTD.equals(device.getName())) {
								return;
							}
							break;
						case BluetoothConstant.XUEYANG:
							if (!device.getName().equals("NOVABT_LE") && !device.getName().equals("POD")) {
								return;
							}
							break;
						case BluetoothConstant.XUEYA:
							if (!BluetoothConstant.XUEYA_JMR.equals(device.getName())
									&& !BluetoothConstant.XUEYA_JMR2.equals(device.getName())
									&& !BluetoothConstant.XUEYA_YE680A_YUYUE.equals(device.getName())
									&& (!device.getName().contains(BluetoothConstant.XUEYA_MAIBOBO1))
									&& (!device.getName().contains(BluetoothConstant.XUEYA_MAIBOBO2))) {
								return;
							}
							break;
						case BluetoothConstant.XUETANG:
							if (!BluetoothConstant.XUETANG_AMX_SANNUO.equals(device.getName())
									&& !BluetoothConstant.XUETANG_WL_1_SANNUO.equals(device.getName())
									&& !BluetoothConstant.XUETANG_YUYUE760_YUYUE.equals(device.getName())
									&& (!device.getName().contains(BluetoothConstant.XUETANG_WEITAI))) {
								return;
							}
							break;
						case BluetoothConstant.NIAOCHANGGUI:
							if (!BluetoothConstant.NIAOJI_HT111A_HANTANG.equals(device.getName())) {
								return;
							}
							break;
						default:
							return;
						}
						List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
								"macAddress = " + "'" + device.getAddress() + "'");
						if (btDevices.size() > 0) {
							// if (btDevices.get(0).isVersion4()) {
							mDeviceName = device.getName();
							NovaLog.e(TAG, device.getName());
							BaseSharedPreferencesUtil.saveStr(mContext, "nova_debug", "deviceName", device.getName());

							bindDeviceData(device);
							// }
						}
					} else {
						return;
					}

				}
			});
		}
	};

	// Code to manage Service lifecycle.
	private final ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName componentName, IBinder service) {
			mBluetoothLeService = ((TJBluetoothLeService.LocalBinder) service).getService();
			NovaLog.e(TAG, "mServiceConnection Unable to initialize BluetoothXXX");
			if (!mBluetoothLeService.initialize()) {
				NovaLog.e(TAG, "mServiceConnection Unable to initialize Bluetooth");
				// btn_start.setClickable(false);
				// tv_bleStatus.setText("手机不支持蓝牙");
			}
			// Automatically connects to the device upon successful start-up
			// initialization.
			mBluetoothLeService.connect(mDeviceAddress);
			isBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName componentName) {
			mBluetoothLeService = null;
			isBound = false;
		}
	};

	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_CONNECTED);
		intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(TJBluetoothLeService.ACTION_DATA_AVAILABLE);

		return intentFilter;
	}

	private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (TJBluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
				// mConnected = true;
				updateConnectionState("已连接GATT");
				// invalidateOptionsMenu();
			} else if (TJBluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
				// mConnected = false;
				updateRestartState("断开GATT连接");
			} else if (TJBluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				// Show all the supported services and characteristics on the
				// user interface.
				// displayGattServices(mBluetoothLeService.getSupportedGattServices());
				updateConnectionState("正在通信");
			} else if (TJBluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				String data = intent.getStringExtra(TJBluetoothLeService.EXTRA_DATA);
				// TODO 完成对数据的显示
				showData(data);
			}
		}

	};

	private void updateConnectionState(final String resourceId) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// tv_bleStatus.setText(resourceId);
				String novaName = BluetoothConstant.getNovaDevice(mDeviceName);
				if (TextUtils.isEmpty(novaName)) {
					showProgressDialog("等待接收数据");
				} else {

					Log.e(TAG, novaName);
					String text = "等待接收" + novaName + "数据";
					try {
						SpannableStringBuilder builder = GlobalContsBlueThooth.setDifferentText(text, 4,
								4 + novaName.length());
						if (builder != null) {
							showProgressDialogBuilder(builder);
						} else {
							showProgressDialog(text);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

				}

			}
		});
	}

	private void updateRestartState(final String resourceId) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {

					// tv_bleStatus.setText(resourceId);
					unbindService(mServiceConnection);
					mBluetoothLeService = null;
					cancelProgressDialog();

					if (!isReceive) {
						// BaseToast.showShortToast(mContext, "连接中断");
						String novaName = BluetoothConstant.getNovaDevice(mDeviceName);
						if (TextUtils.isEmpty(novaName)) {
							showTextDialog("连接中断");
							tv_state.setText("连接中断");
						} else {
							showTextDialog("连接" + novaName + "中断");
							tv_state.setText("连接" + novaName + "中断");
						}
						lay_celiang.setVisibility(View.VISIBLE);
						if (mGattUpdateReceiver != null) {
							mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
							mGattUpdateReceiver = null;
						}

						mBluetoothLeService = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
	}

	private void showData(final String data) {
		isReceive = true;
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				System.out.println(queryIndex + "*********************");
				Log.e("showData()",data + "*********************");
				
				cancelProgressDialog();
				if (BluetoothConstant.XUEYA_JMR.equals(mDeviceName)
						|| BluetoothConstant.XUEYA_JMR2.equals(mDeviceName)) {

					// if (data.length() <= 4) {
					//
					// lay_result.setVisibility(View.GONE);
					// lay_celiang.setVisibility(View.GONE);
					// } else
					if ("测量失败，请重新测量！".equals(data)) {
						lay_result.setVisibility(View.VISIBLE);
						tv_state.setText("测量失败，请重新测量！");
						tv_result.setText("");
					} else if ("臂式血压计电量不足，请及时充电".equals(data)) {

						lay_result.setVisibility(View.VISIBLE);
						tv_state.setText("电量不足，无法完成测量！");
						tv_result.setText("");
					}
					// else if ("冲压失败,无法进行".equals(data)) {
					//
					// lay_result.setVisibility(View.VISIBLE);
					// tv_state.setText("冲压失败，请重新测量！");
					// tv_result.setText("");
					// }
					else {

						lay_result.setVisibility(View.VISIBLE);

						String result = DeviceShowSaveData.getDataShow(data, mDeviceName);
						Log.e("showData()3333",result + "*********************");
						tv_result.setText("测量结果：\n        " + result);
						tv_state.setText("获取测量结果成功");
					}
					lay_celiang.setVisibility(View.VISIBLE);
				} else {
					lay_result.setVisibility(View.VISIBLE);
					lay_celiang.setVisibility(View.VISIBLE);
					// if(TextUtils.isEmpty(mDeviceName)&&isBlooth2){
					// mDeviceName="NOVAEW";
					// }
					if(mDeviceName.contains(BluetoothConstant.XUETANG_WEITAI)){
						mDeviceName=BluetoothConstant.XUETANG_WEITAI;
					}
					String result = DeviceShowSaveData.getDataShow(data, mDeviceName);

					tv_result.setText("测量结果：\n        " + result);

					tv_state.setText("获取测量结果成功");

					// TODO
					if (BluetoothConstant.TIWEN.equals(queryIndex)) {
						if (isBlooth2) {
							// 蓝牙2.0
							if (isServiceRunning(getApplicationContext(),
									"com.novabluetooth.services.bluetooth2.ListenService")) {
								stopService(new Intent(SBCLActivity.this, ListenService.class));
							}

						} else {
							if (mGattUpdateReceiver != null) {
								mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
								mGattUpdateReceiver = null;
							}

							mBluetoothLeService = null;
						}
					} else {
						if (mGattUpdateReceiver != null) {
							mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
							mGattUpdateReceiver = null;
						}

						mBluetoothLeService = null;
					}

				}

			}
		});
	}

	/**
	 * 绑定开始连接设备
	 */
	public void bindDeviceData(BluetoothDevice device) {
		if (mScanning) {
			mScanning = false;
			scanLeDevice(false);
		}

		editor.putString("deviceName", device.getName());
		editor.commit();

		mDeviceAddress = device.getAddress();
		System.out.println(device.getName() + "********************");
		Intent gattServiceIntent = null;
		switch (queryIndex) {
		case BluetoothConstant.TIWEN:
			if (BluetoothConstant.TIWEN_EWQ_HTD.equals(device.getName())
					|| BluetoothConstant.TIWEN_EWENQ_HTD.equals(device.getName())) {
				// Intent gattServiceIntent = new Intent(mContext,
				// TJBluetoothLeService.class);
				gattServiceIntent = new Intent(mContext, TiWenHtdService.class);
			} else if (BluetoothConstant.TIWEN_EWQ_NOVA.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, TiWenNovaService.class);
			}
			break;
		case BluetoothConstant.XUETANG:
			if (BluetoothConstant.XUETANG_AMX_SANNUO.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, XueTangAWXSanNuoService.class);
			} else if (BluetoothConstant.XUETANG_WL_1_SANNUO.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, XueTangWL1SanNuoService.class);
			} else if(device.getName().contains(BluetoothConstant.XUETANG_WEITAI)){
				gattServiceIntent = new Intent(mContext, WeiTaiXueTangService.class);
			}
			break;
		case BluetoothConstant.TIZHONG:
			if (BluetoothConstant.TIZHONG_NOVA.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, TiZhongNovaService.class);
			}

		case BluetoothConstant.XUEYANG:
			if (BluetoothConstant.XUEYANG_LIKANG_KRK.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, XueYangKRKService.class);
			} else if (BluetoothConstant.XUEYANG_NOVA.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, XueYangNovaService.class);
			}
			break;
		case BluetoothConstant.XUEYA:
			if (BluetoothConstant.XUEYA_JMR.equals(device.getName())
					|| BluetoothConstant.XUEYA_JMR2.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, XueYaB61TJMRService.class);
			} else if (BluetoothConstant.XUEYA_YE680A_YUYUE.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, XueYaYuYue760Service.class);
			}
			break;
		case BluetoothConstant.NIAOCHANGGUI:
			if (BluetoothConstant.NIAOJI_HT111A_HANTANG.equals(device.getName())) {
				gattServiceIntent = new Intent(mContext, NiaoJiht111AHanTangService.class);
			}
			break;

		default:
			break;
		}

		if (gattServiceIntent != null) {
			mContext.bindService(gattServiceIntent, mServiceConnection, mContext.BIND_AUTO_CREATE);
			
		}
	}

	/**
	 * 关闭并退出
	 * 
	 * @author 王婷婷
	 * @date 2017年3月18日 下午5:13:21
	 */
	public void closeAndExit() {
		System.out.print("NoticeService关闭");
		scanLeDevice(false);
		try {

			if (isRegisterReceiver) {
				if (mGattUpdateReceiver != null) {
					isRegisterReceiver = false;
					mContext.unregisterReceiver(mGattUpdateReceiver);
				}
			}
			if (isBound) {
				isBound = false;
				if (mServiceConnection != null) {
					mContext.unbindService(mServiceConnection);
				}
			}
			if (mBluetoothLeService != null) {
				mBluetoothLeService.close();
				mBluetoothLeService = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 蓝牙4.0
		closeAndExit();
		if (msgReceiver != null) {
			unregisterReceiver(msgReceiver);
		}
		// 蓝牙2.0
		if (isServiceRunning(getApplicationContext(), "com.novabluetooth.services.bluetooth2.ListenService")) {
			stopService(new Intent(SBCLActivity.this, ListenService.class));
		}
	}

	/**
	 * 心电图图片
	 * 
	 * @author 王婷婷
	 * @date 2017年7月18日 下午5:08:58
	 */
	private void initEcgJpg(Intent intent) {
		// intent.getStringExtra("tj_result")
		if (intent.hasExtra("JPG_URL")) {
			String url = intent.getStringExtra("JPG_URL");
			Log.w("ttt", url);
			// String
			// url="/storage/emulated/0/ECGDATA/JPEG/-20160315132210.jpeg";
			if (!TextUtils.isEmpty(url)) {
				Bitmap bitmap = getLocalBitmap(url);
				show_img.setImageBitmap(bitmap);
				show_img.setVisibility(View.VISIBLE);
				queryIndex = BluetoothConstant.ECG;
				bt_cklsjl.setText("查看心电历史记录");
			} else {
				show_img.setVisibility(View.GONE);
			}
		}

	}

	public Bitmap getLocalBitmap(String url) {

		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		isBlooth2 = SPUtil.getisBlooth2(SBCLActivity.this, false);
		mContext.getApplicationContext().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		if (mBluetoothLeService != null) {
			final boolean result = mBluetoothLeService.connect(mDeviceAddress);
			Log.e(TAG, "onResume Connect request result=" + result);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (mGattUpdateReceiver != null) {
			mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
		}
	}

	/**
	 * 初始化蓝牙2.0
	 * 
	 * @author 王婷婷
	 * @date 2017年8月1日 下午3:47:36
	 */
	private void initBluetooth2() {
		// 2.0与4.0蓝牙同时开启，第一阶段做2.0尿机
		getBoolthQuanXian();
		// 蓝牙2.0 的尿机
		BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			showTextDialog("本机没有找到蓝牙硬件或驱动！");
		} else {
			if (!mBluetoothAdapter.isEnabled()) {
				showTextDialog("蓝牙没有打开！");
			} else {

				// //启动修改蓝牙可见性的Intent
				// Intent intent = new
				// Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				// //设置蓝牙可见性的时间，方法本身规定最多可见300秒
				// intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
				// 300);
				// startActivity(intent);

				if (!isServiceRunning(getApplicationContext(), "com.novabluetooth.services.bluetooth2.ListenService")) {
					Log.w(TAG, "initBluetooth2 开始测量，ListenService没有运行，开启服务");
					showProgressDialog("正在搜索设备");
					startService(new Intent(SBCLActivity.this, ListenService.class));
				}

			}
		}
	}

	public void getBoolthQuanXian() {
		if (ContextCompat.checkSelfPermission(this,
				Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			// 请求权限
			ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION },
					MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
			// 判断是否需要 向用户解释，为什么要申请该权限
			if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
				Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
			}
		}
	}

	// 蓝牙服务判断
	public static boolean isServiceRunning(Context context, String serviceName) {
		boolean isRunning = false;
		android.app.ActivityManager am = (android.app.ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
		List<android.app.ActivityManager.RunningServiceInfo> infos = am.getRunningServices(500);
		for (android.app.ActivityManager.RunningServiceInfo info : infos) {
			if (info.service.getClassName().equals(serviceName)) {
				Log.e(TAG, "initBluetooth2服务已经运行");
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

}
